package com.khyr.Service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.khyr.Dao.*;
import com.khyr.Service.CheckItemService;
import com.khyr.entity.*;
import com.khyr.feign.UserFeign;
import com.khyr.vo.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author ：lyk
 * @date ：Created in 2025/3/11 20:48
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class CheckItemServiceImpl implements CheckItemService {
    @Autowired
    private CheckItemDao checkItemDao;
    @Autowired
    private HisCareOrderItemDao hisCareOrderItemDao;
    @Autowired
    private HisCheckResultDao hisCheckResultDao;
    @Autowired
    private HisCareOrderDao hisCareOrderDao;
    @Autowired
    private CareHistoryDao careHistoryDao;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private UserFeign userFeign;
    @Override
    public List<CheckItem> selectAllCheckItem() {
        return checkItemDao.selectList(null);
    }

    @Override
    public List<CareOrderItem> queryNeedCheckItem(QueryParamsVO queryParamsVO) {
        QueryWrapper<CareOrderItem> queryWrapper=new QueryWrapper<>();
        QueryWrapper<HisCheckResult> hisCheckResultQueryWrapper = new QueryWrapper<>();
        hisCheckResultQueryWrapper.like("reg_id",queryParamsVO.getRegId());
        List<HisCheckResult> hisCheckResults = hisCheckResultDao.selectList(hisCheckResultQueryWrapper);
        ArrayList<String> CocId = new ArrayList<>();
        for (HisCheckResult hisCheckResult : hisCheckResults) {
            CocId.add(hisCheckResult.getCocId());
        }
        if (!CocId.isEmpty()) {
            queryWrapper.in("item_id", CocId);
        }
        List<String> checkItemIds = queryParamsVO.getCheckItemIds();
        if (checkItemIds == null){
            return null;
        }
        queryWrapper.in("item_ref_id", checkItemIds);
        queryWrapper.eq("item_type","1");
        queryWrapper.eq("status","1");
        // 执行查询并返回结果
        return hisCareOrderItemDao.selectList(queryWrapper);
    }

    @Override
    public QueryCheckItemByItemIdBackVo queryCheckItemByItemId(String itemId) {
        CareOrderItem careOrderItem = hisCareOrderItemDao.selectById(itemId);
        String coId = careOrderItem.getCoId();
        CareOrder careOrder = hisCareOrderDao.selectById(coId);
        CareHistory careHistory = careHistoryDao.selectById(careOrder.getChId());
        return new QueryCheckItemByItemIdBackVo(
                careOrder,
                careOrderItem,
                careHistory
        );
    }

    @Override
    public void startCheck(QueryCheckItemByItemIdBackVo queryCheckItemByItemIdBackVo) {
        String token = request.getHeader("token");


        HisCheckResult hisCheckResult = new HisCheckResult(
                queryCheckItemByItemIdBackVo.getItem().getItemId(),
                Integer.valueOf(queryCheckItemByItemIdBackVo.getItem().getItemRefId()),
                queryCheckItemByItemIdBackVo.getItem().getItemName(),
                queryCheckItemByItemIdBackVo.getItem().getAmount(),
                queryCheckItemByItemIdBackVo.getCareHistory().getRegId(),
                null,
                null,
                queryCheckItemByItemIdBackVo.getCareHistory().getPatientId(),
                queryCheckItemByItemIdBackVo.getCareHistory().getPatientName(),
                "0",
                new Date(),
                new Date(),
                userFeign.getUserInfo(token).getData().getUserName(),
                "admin"
        );
        hisCheckResultDao.insert(hisCheckResult);
        CareOrderItem careOrderItem = queryCheckItemByItemIdBackVo.getItem();
        System.out.println(careOrderItem);
        careOrderItem.setStatus("2");
        hisCareOrderItemDao.updateById(careOrderItem);
    }

    @Override
    public Page<HisCheckResult> queryAllCheckingResultForPage(QueryAllCheckingResultForPageVo queryAllCheckingResultForPageVo) {
        QueryWrapper<HisCheckResult> queryWrapper=new QueryWrapper<>();
        if (queryAllCheckingResultForPageVo.getRegId() != null) {
            queryWrapper.like("reg_id", queryAllCheckingResultForPageVo.getRegId());
        }
        if(StringUtils.hasText(queryAllCheckingResultForPageVo.getPatientName())){
            queryWrapper.like("patient_name", queryAllCheckingResultForPageVo.getPatientName());
        }
        if (queryAllCheckingResultForPageVo.getCheckItemIds() != null) {
            queryWrapper.in("check_item_id", queryAllCheckingResultForPageVo.getCheckItemIds());
        }
        queryWrapper.eq("result_status", "0");
        Page<HisCheckResult> page = new Page<>(queryAllCheckingResultForPageVo.getPageNum(), queryAllCheckingResultForPageVo.getPageSize());
        return hisCheckResultDao.selectPage(page, queryWrapper);
    }

    @Override
    public void completeCheckResult(CompleteCheckResultVo completeCheckResultVo) {
        HisCheckResult hisCheckResult = hisCheckResultDao.selectById(completeCheckResultVo.getItemId());
        hisCheckResult.setResultMsg(completeCheckResultVo.getResultMsg());
        List<String> resultImg = completeCheckResultVo.getResultImg();
        List<Map<String, String>> resultImgList = new ArrayList<>();
        for (String imgUrl : resultImg) {
            Map<String, String> imgMap = new HashMap<>();
            imgMap.put("url", imgUrl);
            // 提取文件名
            imgMap.put("name", imgUrl.substring(imgUrl.lastIndexOf("/") + 1));
            resultImgList.add(imgMap);
        }
        // 将 List<Map<String, String>> 转化为 JSON 字符串
        String resultImgJson = JSON.toJSONString(resultImgList);
        hisCheckResult.setResultImg(resultImgJson);
        hisCheckResult.setResultStatus("1");
        hisCheckResult.setUpdateTime(new Date());
        hisCheckResultDao.updateById(hisCheckResult);
    }

    @Override
    public R<Page<HisCheckResult>> queryAllCheckResultForPage(QueryAllCheckingResultForPageVo queryAllCheckingResultForPageVo) {
        QueryWrapper<HisCheckResult> queryWrapper=new QueryWrapper<>();
        // 根据 noticeVo 中的条件动态构建查询条件
        if (queryAllCheckingResultForPageVo.getRegId() != null) {
            queryWrapper.like("reg_id", queryAllCheckingResultForPageVo.getRegId());
        }
        if(StringUtils.hasText(queryAllCheckingResultForPageVo.getPatientName())){
            queryWrapper.like("patient_name", queryAllCheckingResultForPageVo.getPatientName());
        }
        Page<HisCheckResult> page = new Page<>(queryAllCheckingResultForPageVo.getPageNum(), queryAllCheckingResultForPageVo.getPageSize());
        Page<HisCheckResult> p = hisCheckResultDao.selectPage(page, queryWrapper);
        if (p != null){
            return new R<>(200,"查询成功",p);
        }else {
            return new R<>(500,"查询失败",null);
        }
    }
}
